const router = require('koa-router')()
const {
  getList,
  getDetail,
  newBlog,
  updateBlog,
  delBlog
} = require('../controller/blog')
const { SuccessModel, ErrorModel } = require('../model/resModel')
const loginCheck = require('../middleware/loginCheck')

router.prefix('/api/blog')

// 获取博客列表
router.get('/list', async (ctx, next) => {
  let author = ctx.query.author || ''
  let keyword = ctx.query.keyword || ''

  if (ctx.query.isadmin) {
    // 自定义日志
    console.log('is admin')
    // 个人主页
    if (ctx.session.username == null) {
      // 未登录
      console.log('is admin, but no login')
      ctx.body = new ErrorModel('未登录')
      return
    }
    // 强制查询自己的博客
    author = ctx.session.username
  }

  const listData = await getList(author, keyword)
  ctx.body = new SuccessModel(listData)
});

// 获取博客详情
router.get('/detail', async (ctx, next) => {
  const { id } = ctx.query
  const data = await getDetail(id)

  ctx.body = new SuccessModel(data)
});

// 新建一篇博客
router.post('/new', loginCheck, async (ctx, next) => {
  const body = ctx.request.body
  body.author = ctx.session.username
  const data = await newBlog(body)

  ctx.body = new SuccessModel(data)
});

// 更新一篇博客
router.post('/update', loginCheck, async (ctx, next) => {
  const { id } = ctx.query
  const val = await updateBlog(id, ctx.request.body)

  if (val) {
    ctx.body = new SuccessModel('更新博客成功！')
  } else {
    ctx.body = new ErrorModel('更新博客失败...')
  }
});

// 删除一篇博客
router.post('/del', loginCheck, async (ctx, next) => {
  const { id } = ctx.query
  ctx.query.author = ctx.session.username
  const val = await delBlog(id, ctx.query.author)

  if (val) {
    ctx.body = new SuccessModel('删除博客成功！')
  } else {
    ctx.body = new ErrorModel('删除博客失败...')
  }
});

module.exports = router
